package io.renren.modules.wms.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import io.renren.common.utils.Constant;
import io.renren.common.utils.Query;
import io.renren.common.utils.excel.*;
import io.renren.modules.wms.dao.JDEMapper;
import io.renren.modules.wms.dao.WmsDataDao;
import io.renren.modules.wms.entity.Product;
import io.renren.modules.wms.entity.Ratio;
import io.renren.modules.wms.entity.Unit;
import io.renren.modules.wms.entity.WmsDataEntity;
import io.renren.modules.wms.service.StockCompare;
import io.renren.modules.wms.service.WmsDataService;
import io.renren.modules.wms.vo.FuleImport;
import io.renren.modules.wms.vo.GangYuImport;
import io.renren.modules.wms.vo.JdeImport;
import io.renren.modules.wms.vo.WmsImport;
import lombok.NonNull;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import io.renren.common.utils.PageUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import static io.renren.common.utils.Constant.FROM_DB.*;


@Service("wmsDataService")
public class WmsDataServiceImpl extends ServiceImpl<WmsDataDao, WmsDataEntity> implements WmsDataService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JDEMapper jdeMapper;

    @Resource
    private StockCompare stockCompare;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WmsDataEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!TextUtils.isBlank(key)){
            queryWrapper.eq("from_db", key);
        }

        IPage<WmsDataEntity> page = this.page(new Query<WmsDataEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public ResponseMsg importExcel(MultipartFile file, int type) {
        ImportParam param = new ImportParam<>();
        param.setFile(file);
        switch (type) {
            case 1:
                param.setHeadNum(3);
                param.setImportBeanClazz(GangYuImport.class);
                param.setHandleListener(new UnderHandleListener(Constant.FROM_DB.GANGYU_MANUAL));
                param.setFileExtension(ExcelTypeEnum.XLS);
                break;
            case 2:
                param.setImportBeanClazz(FuleImport.class);
                param.setHandleListener(new UnderHandleListener(Constant.FROM_DB.FULE_MANUAL));
                break;
            case 3:
                param.setImportBeanClazz(JdeImport.class);
                param.setHandleListener(new UnderHandleListener(Constant.FROM_DB.JDE_MANUAL));
                break;
            default:
                break;
        }
        return EasyExcelUtil.importExcel(param);
    }

    @Override
    public ResponseMsg capture() {
        List<WmsImport> wmsImports = new ArrayList<>();
        List<WmsImport> imports = new ArrayList<>();
        // 抓取刚玉数据库
        imports = baseMapper.selectAllGangyuStock();
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(GANGYU_CAPTURE));
            wmsImports.addAll(imports);
        }
        // 抓取富勒数据库
        imports = baseMapper.selectAllFuleStock();
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(FULE_CAPTURE));
            wmsImports.addAll(imports);
        }
        // 抓取JDE数据库
        imports = baseMapper.selectAllJdeStock();
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(JDE_CAPTURE));
            wmsImports.addAll(imports);
        }
        // 抓取外部JDE数据库
        imports = baseMapper.selectOutJdeStock("2023-11-15");
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(JDE_CAPTURE_OUT));
            wmsImports.addAll(imports);
        }
        // 外部抓取的WMS数据
        imports = baseMapper.selectOutWmsStock("2023-11-15");
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(WMS_CAPTURE_OUT));
            wmsImports.addAll(imports);
        }
        // 抓取开未发的JDE数据
        imports = baseMapper.selectKWFStock();
        if (!CollectionUtils.isEmpty(imports)) {
            imports.forEach(item -> item.setFromDb(JDE_CAPTURE_KWF));
            wmsImports.addAll(imports);
        }
        if (CollectionUtils.isEmpty(wmsImports)) {
            return ResponseMsgUtil.error("无抓取数据");
        }
        handleData(wmsImports, null, false);
        return ResponseMsgUtil.success("抓取成功");
    }

    @Override
    public void deleteAll() {
        baseMapper.delete(new QueryWrapper<>());
    }

    @Override
    public ResponseMsg compare() {
        stockCompare.handle();
        return ResponseMsgUtil.success("库存成功处理");
    }

    public void handleData(List<WmsImport> excelData, String from, boolean isSetFrom) {

        Map<String, Product> productMap = new HashMap<>();
        List<Product> productList = jdeMapper.selectAllProduct();
        productList.forEach(item -> productMap.put(item.getGOODID(), item));
        Map<String, Ratio> ratioMap = new HashMap<>();
        jdeMapper.selectAllRatio().forEach(item -> ratioMap.put(item.IMLITM + item.getUMUM() + item.getUMRUM(), item));
        Map<String, Unit> enUnitMap = new HashMap<>();
        jdeMapper.selectAllUnit().forEach(item -> enUnitMap.put(item.getDRKY(), item));
        Map<String, Unit> chUnitMap = new HashMap<>();
        jdeMapper.selectAllUnit().forEach(item -> chUnitMap.put(item.getDRDL01(), item));

        List<WmsDataEntity> wmsDataEntityList = new ArrayList<>();

        for (WmsImport beanFromExcel : excelData) {
            if (TextUtils.isBlank(beanFromExcel.getNum())
                    || TextUtils.isBlank(beanFromExcel.getBatch())
                    || TextUtils.isBlank(beanFromExcel.getUnit())
                    || TextUtils.isBlank(beanFromExcel.getName())
                    || TextUtils.isBlank(beanFromExcel.getSpec())
                    || TextUtils.isBlank(beanFromExcel.getCode())) {
                continue;
            }
            WmsDataEntity insertBean = new WmsDataEntity()
                    .setCode(beanFromExcel.getCode())
                    .setName(beanFromExcel.getName())
                    .setSpec(beanFromExcel.getSpec())
                    .setBatch(beanFromExcel.getBatch())
                    .setNumOriginal(beanFromExcel.getNum())
                    .setNumNow(beanFromExcel.getNum())
                    .setUnitOriginal(beanFromExcel.getUnit())
                    .setUnitNow(beanFromExcel.getUnit())
                    .setExtra1(beanFromExcel.getExtra1())
                    .setExtra2(beanFromExcel.getExtra2())
                    .setExtra3(beanFromExcel.getExtra3())
                    .setExtra4(beanFromExcel.getExtra4())
                    .setExtra5(beanFromExcel.getExtra5())
                    .setUpdateTime(new Date());
            if (isSetFrom) {
                insertBean.setFromDb(from);
            } else {
                insertBean.setFromDb(beanFromExcel.getFromDb());
            }
            if (productMap.containsKey(insertBean.getCode())) {
                changeUnit(insertBean, productMap, ratioMap, enUnitMap, chUnitMap);
                insertBean.setNumNow(handleInt(insertBean.getNumNow()));
                wmsDataEntityList.add(insertBean);
            }
        }
        // 清空当前类型的
        if (isSetFrom) {
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", from));
        }else {
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", GANGYU_CAPTURE));
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", FULE_CAPTURE));
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", JDE_CAPTURE));
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", JDE_CAPTURE_OUT));
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", WMS_CAPTURE_OUT));
            baseMapper.delete(new QueryWrapper<WmsDataEntity>().eq("from_db", JDE_CAPTURE_KWF));
        }
        // 批量插入
        Lists.partition(wmsDataEntityList, 500).forEach(baseMapper::batchInsert);
    }

    public class UnderHandleListener implements ImportHandleListener {

        private String from;

        public UnderHandleListener(String from) {
            this.from = from;
        }

        @Override
        public void handle(@NonNull List excelData, @NonNull StringBuilder errorInfo, String handleUserName) {
            handleData(excelData, from, true);
        }
    }

    private void changeUnit(WmsDataEntity stock,
                            Map<String, Product> productMap,
                            Map<String, Ratio> ratioMap,
                            Map<String, Unit> enUnitMap,
                            Map<String, Unit> chUnitMap) {
        if (stock == null
                || CollectionUtils.isEmpty(productMap)
                || CollectionUtils.isEmpty(ratioMap)
                || CollectionUtils.isEmpty(enUnitMap)
                || CollectionUtils.isEmpty(chUnitMap)) {
            logger.error("转换数据失败1");
            return;
        }
        if (TextUtils.isBlank(stock.getCode())
                || TextUtils.isBlank(stock.getNumOriginal())) {
            logger.error("转换数据失败2");
            return;
        }
        Product product = productMap.get(stock.getCode());
        if (product == null) {
            return;
        }
        // 最小计量单位
        String baseUnitCode = product.getBASEUNITCODE();
        if (TextUtils.isBlank(baseUnitCode)) {
            return;
        }
        if (TextUtils.isBlank(stock.getUnitOriginal())) {
            return;
        }
        if (chUnitMap.get(stock.getUnitOriginal().trim()) == null) {
            return;
        }
        // 将中文转成英文
        String fromUnitCode = chUnitMap.get(stock.getUnitOriginal().trim()).DRKY;
        if (TextUtils.isBlank(fromUnitCode)) {
            fromUnitCode = stock.getUnitOriginal().trim();
        }
        // 找到等比关系
        String key = product.getGOODID().trim() + fromUnitCode.trim() + baseUnitCode.trim();
        if (ratioMap.get(key) == null) {
            return;
        }
        Double ratio = ratioMap.get(key).ratio;
        if (ratio == null) {
            return;
        }
        String newNum = new BigDecimal(stock.getNumOriginal()).multiply(new BigDecimal(ratio)).toString();
        stock.setNumNow(newNum);
        // 转成中文
        String fromUnit = enUnitMap.get(baseUnitCode.trim()).DRDL01;
        if (!TextUtils.isBlank(fromUnit)) {
            stock.setUnitNow(fromUnit);
        }
    }

    /**
     * 小数四舍五入
     */
    private String handleInt(String num){
        String num2 = "0";
        try {
            num2 = String.valueOf(Math.round(Double.parseDouble(num)));
        }catch (Exception e){
            e.printStackTrace();
        }
        return num2;
    }

}